package com.crm.sys.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.crm.base.annotation.Authority;
import com.crm.base.controller.BaseController;
import com.crm.customers.model.ContactsDynamicInfo;
import com.crm.customers.model.CustomerContacts;
import com.crm.customers.model.CustomerInfo;
import com.crm.customers.service.ContactsDynamicInfoService;
import com.crm.customers.service.CustomerContactsService;
import com.crm.customers.service.CustomerService;
import com.crm.im.core.model.Message;
import com.crm.im.core.session.DefaultSessionManager;
import com.crm.im.core.session.IMSession;
import com.crm.sys.model.Announcement;
import com.crm.sys.model.ApproveConfigure;
import com.crm.sys.model.ApproveConfigureItem;
import com.crm.sys.model.CallLog;
import com.crm.sys.model.City;
import com.crm.sys.model.Configure;
import com.crm.sys.model.ConfigureItem;
import com.crm.sys.model.Department;
import com.crm.sys.model.FilesInfo;
import com.crm.sys.model.Log;
import com.crm.sys.model.Province;
import com.crm.sys.model.RobotMessage;
import com.crm.sys.model.RobotMessageArticle;
import com.crm.sys.model.Role;
import com.crm.sys.model.SysMessage;
import com.crm.sys.model.SysTerm;
import com.crm.sys.model.TokenPackage;
import com.crm.sys.push.DefaultMessagePusher;
import com.crm.sys.push.SystemMessagePusher;
import com.crm.sys.service.ApproveConfigureService;
import com.crm.sys.service.FilesInfoService;
import com.crm.sys.service.SysService;
import com.crm.user.model.UserAccount;
import com.crm.user.model.UserInfo;
import com.crm.user.service.UserService;
import com.crm.util.CommonUtil;
import com.crm.util.Constants;
import com.crm.util.CrmUtil;
import com.crm.util.HttpRequester;
import com.crm.util.Pager;
import com.crm.util.PropertyReader;
import com.crm.util.RandomString;
import com.crm.util.StringUtil;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.nimbusds.oauth2.sdk.AuthorizationCode;
import com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse;
import com.nimbusds.openid.connect.sdk.AuthenticationResponse;
import com.nimbusds.openid.connect.sdk.AuthenticationResponseParser;
import com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse;
@Controller
public class SysController extends BaseController {
	@Autowired
	private SysService sysService;
	@Autowired
	private DefaultMessagePusher messagePusher;
	@Autowired
	private SystemMessagePusher systemMessagePusher;
	@Autowired
	private UserService userService;
	@Autowired
	private DefaultSessionManager sessionManager;
	@Autowired
	private ApproveConfigureService approveConfigureService;
	@Autowired
	private CustomerContactsService customerContactsService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private ContactsDynamicInfoService contactsDynamicInfoService;
 
	
	private  String getRobotMessage(String user,String info){
		  String message = "";
		 try{
			 
				Document doc = Jsoup.connect("http://www.tuling123.com/openapi/api").timeout(62000).data("key",Constants.ROBOTKEY).data("userid",user).data("info",info).post();
				//System.getProperty("line.separator")
				String msgStr = doc.select("body").html().replace("&quot;", "'");
						msgStr = msgStr.replace("\r\n", "<br>");
						msgStr = msgStr.replace("<br />", "") ;
				RobotMessage msg=	JSON.parseObject(msgStr,RobotMessage.class);
				switch (msg.getCode()) {
				case 100000:
					message = msg.getText();
					break; 
				case 200000:
					message = msg.getText() +"   "+msg.getUrl();
					break;
				case 302000:
					List<RobotMessageArticle>  sublist = JSON.parseArray(msg.getList(), RobotMessageArticle.class);
					String html ="";
					for(RobotMessageArticle a :sublist){
						 html+="a("+a.getDetailurl()+")["+a.getArticle()+"] <br><br>";
					}
					message = html;
					break;
				case 308000:
					List<RobotMessageArticle>  sublistOne = JSON.parseArray(msg.getList(), RobotMessageArticle.class);
					String htmlOne ="";
					for(RobotMessageArticle a :sublistOne){
						htmlOne+="菜名："+a.getName()+"<br>用料："+a.getInfo()+"  <br>详情地址:a("+a.getDetailurl()+")["+a.getDetailurl()+"]      <br><br>";
					}
					message = htmlOne;
				break;
				default:
					break;
				}
				
				
			}catch(Exception e){
				e.printStackTrace();
			}
		 
		 return message;
	}
	
	 @RequestMapping(value = "/sys/callcenter", method = RequestMethod.GET)
	 public String call(HttpServletRequest request) throws Exception {
	          
		   String param = request.getParameter("param1");
		    String decodeStr =new String(Constants.decoder.decodeBuffer(param), "UTF-8");
		    String[] strs = decodeStr.split("&");
		    Map<String, String> m = new HashMap<String, String>();
		    for(String s:strs){
		    String[] ms = s.split("=");
		       m.put(ms[0], ms[1]);
		    }
		    String phone = m.get("dhhm");
		    CustomerContacts ccontacts =new CustomerContacts();
		    ccontacts.setPhone(phone);
		    CustomerContacts  cc =   customerContactsService.getcustconlistByphone(ccontacts);
		    if(cc!=null&&cc.getCusid()!=null) {
		    	CustomerInfo   cusinfo = 	customerService.getCustomerInfoById(cc.getCusid());
				ContactsDynamicInfo cdinfo = new ContactsDynamicInfo();
				cdinfo.setCusid(cc.getCusid());
				cdinfo.setState(2);
				Integer pageNo1 = 1;
				Integer pageSize = 6;
				List<ContactsDynamicInfo> lxlist = contactsDynamicInfoService.getAllcdinfolist(cdinfo, pageNo1, pageSize);
		    	request.setAttribute("info", cusinfo);
		      	request.setAttribute("lxlist", lxlist);
		      	request.setAttribute("uname", cc.getName());
		    }
		  	request.setAttribute("phone", phone);
		   return "callcenter/callinfo";
		      /*//判断是否已经登录aliyun
		        if(StringUtils.isNotEmpty(getLoginUser().getInfo().getAccessToken())) {
		        	 request.setAttribute("instanceId", Constants.CALLCENTER.get("instanceId"));
		        	  return "callcenter/call";
		        }else {
		        	return "redirect:/auth";
		        }*/
		      
	    }
	 
	 
	 @RequestMapping(value = "/savesms")
	 public String saveSms(HttpServletRequest httpServletRequest) throws Exception {
		  String contentType = httpServletRequest.getContentType();
		  System.out.println(contentType);
		
		   int totalbytes = httpServletRequest.getContentLength();
	        // 容纳请求消息实体的字节数组
	        byte[] dataOrigin = new byte[totalbytes];
	        DataInputStream in = null;
		     // 得到请求消息的数据输入流
	        try {
	             in = new DataInputStream(httpServletRequest.getInputStream());
	             in.readFully(dataOrigin); // 根据长度，将消息实体的内容读入字节数组dataOrigin中
	             in.close(); // 关闭数据流
	        }catch(Exception e) {
	        }finally {
				  if(in!=null) {
					  in.close();
				  }
			} 
        String reqcontent = new String(dataOrigin); // 从字节数组中得到表示实体的字符串
        
        String decodeStr =new String(Constants.decoder.decodeBuffer(reqcontent), "UTF-8");
		Document doc = Jsoup.parse(decodeStr);	
		Element  record = doc.select("record").get(0);
        
     //   CallLog   clog =   getData(reqcontent,httpServletRequest); 
		 
		 return "";
		 
	 }
	 
	 
	 
	 
		@RequestMapping(value = "/sys/message",produces="text/html;charset=UTF-8", method = RequestMethod.GET)
		 @ResponseBody
		public String sysMessage(HttpServletResponse response,HttpServletRequest request,
				RedirectAttributes redirectAttributes) throws Exception{
			SysMessage ms = new SysMessage();
			ms.setType(2);
			ms.setReceiveuser(0L);
			List<SysMessage>  msgList = sysService.getMessageList(ms);
			return JSONArray.toJSONString(msgList);
		}
		
		
		private    CallLog   getData(String data,HttpServletRequest request) {
			CallLog  clog = null;
			 try {
				    String decodeStr =new String(Constants.decoder.decodeBuffer(data), "UTF-8");
					Document doc = Jsoup.parse(decodeStr);	
					Element  record = doc.select("record").get(0);
					String type = record.attr("callType");
					String recordURL = record.attr("recordURL");
					if(type.equals("1")||type.equals("2")) {
						  if(StringUtils.isEmpty(recordURL)) {
						     return clog;
						  }
					} 
					String code = record.attr("code");
					String calledNum = record.attr("calledNum").replace("Phone_Unknow", "");
					String callerNum = record.attr("callerNum").replace("Phone_Unknow", "");
					String startTime = record.attr("startTime");
					String timeLength = record.attr("timeLength");
					String ownerAcc = record.attr("ownerAcc");
					String followId[] = record.attr("followId").split("-");
				
				    clog  = new CallLog();
				    clog.setType(Integer.parseInt(type));
				    clog.setFileUrl(recordURL);
				    clog.setCode(code);
				    clog.setCalee(calledNum);
				    clog.setCaller(callerNum);
				    clog.setStartTime(startTime);
				    try {
				        clog.setCusid(Long.parseLong(followId[0]));
				    }catch(Exception e) {
				    }
				    clog.setOwnerAcc(ownerAcc);
				    if(followId.length>1) {
				    	   clog.setCreateuser(Long.parseLong(followId[1]));
				    }
				    clog.setTime(Integer.parseInt(timeLength));
				    try {
				    	clog.setFilePath(recordURL);
				    	 /*  String path=request.getSession().getServletContext().getRealPath("upload/audio/user/");
						    CommonUtil.downLoadFromUrl(recordURL.replace("&amp;","&"),   code+".spx", path);  
						    clog.setFilePath("/upload/audio/user/"+ code+".spx");*/
				    }catch(Exception e) {
				    	 e.printStackTrace();
				    }
			 }catch(Exception e) {
				 e.printStackTrace();
			 }
			return clog;
		
		}
		//, method = RequestMethod.POST
		
		@RequestMapping(value = "/sys/calllogsave")
		/* @ResponseBody*/
		    public void callLogSave(Principal principal,HttpServletResponse response, HttpServletRequest httpServletRequest) throws Exception {
			
			  String contentType = httpServletRequest.getContentType();
			  System.out.println(contentType);
			
			   int totalbytes = httpServletRequest.getContentLength();
		        // 容纳请求消息实体的字节数组
		        byte[] dataOrigin = new byte[totalbytes];
		        DataInputStream in = null;
			     // 得到请求消息的数据输入流
		        try {
		             in = new DataInputStream(httpServletRequest.getInputStream());
		             in.readFully(dataOrigin); // 根据长度，将消息实体的内容读入字节数组dataOrigin中
		             in.close(); // 关闭数据流
		        }catch(Exception e) {
		        }finally {
					  if(in!=null) {
						  in.close();
					  }
				} 
	         String reqcontent = new String(dataOrigin); // 从字节数组中得到表示实体的字符串
	         CallLog   clog =   getData(reqcontent,httpServletRequest); 
				try { 
					//System.out.println(new String(Constants.decoder.decodeBuffer(reqcontent), "UTF-8"));
					response.setContentType("type=text/html;charset=UTF-8"); 
					String outstr = "";
					   if(clog!=null) {
				        	sysService.saveCallLog(clog);
				        	outstr = "<xml><result>1</result><body></body></xml>";
				        }	
				
					final byte[] textByte = outstr.getBytes("UTF-8");
					//编码
					final String encodedText = Constants.encoder.encode(textByte);
					response.getWriter().write(encodedText); 
				} catch (Exception e) { 
					e.printStackTrace(); 
				} 
					return; 
	      
	        
		
		/*	Enumeration em = httpServletRequest.getParameterNames();
			 while (em.hasMoreElements()) {
			    String name = (String) em.nextElement();
			    String[] value = httpServletRequest.getParameterValues(name);
			    System.out.println(name+"----"+value);
			}*/
			//String  sss= httpServletRequest.getParameter("param1");
	
			 
			//return "<xml><result>1</result><body></body></xml>";
			
			//以下用于阿里云呼叫中心
			/*String connid = httpServletRequest.getParameter("connid");
			String caller = httpServletRequest.getParameter("caller");
			String calee = httpServletRequest.getParameter("calee");
			String contactId = httpServletRequest.getParameter("contactId");
			CallLog  cl = new CallLog();
			cl.setCalee(calee);
			cl.setConnid(connid);
			cl.setCaller(caller);
			cl.setContactId(contactId);
			cl.setCreateuser(getLoginUser().getId());
			sysService.saveCallLog(cl);
			HttpSession  session = 	httpServletRequest.getSession();
			String contactIdLast = (String)session.getAttribute("contactId");
			 
			session.setAttribute("contactId", contactId);
			return "";*/
				 
			
		}	
		
	
	 @RequestMapping(value = "/aliyun/ccc/api", method = RequestMethod.POST)
	 @ResponseBody
	    public String call(Principal principal, HttpServletRequest httpServletRequest) throws Exception {
			// try {
				   String action = httpServletRequest.getParameter("action");
		           String request = httpServletRequest.getParameter("request");
		           String token = getLoginUser().getInfo().getAccessToken();
		           //String token =  (String)httpServletRequest.getSession().getAttribute("tokenid");
		           
		           TokenPackage tokenPackage = null;
		            try {
		                tokenPackage =  getLoginUser().getTokenPackage();//  TokenPackage.parse(token);
		                if(tokenPackage==null  || tokenPackage.isExpire()) {
		                	   tokenPackage =  TokenPackage.parse(token);
		                	    String accessToken = refreshAccessToken(tokenPackage.getRefreshToken(),
	                            httpServletRequest.getRequestURI());
		                	    try {
					                tokenPackage = TokenPackage.parse(accessToken);
					                getLoginUser().setTokenPackage(tokenPackage);
					            } catch (Exception e) {
					            } 
		                	    
		                	    if(tokenPackage!=null&&StringUtils.isNotEmpty(tokenPackage.getRefreshToken())) {
		                	    	    getLoginUser().getInfo().setAccessToken(accessToken);
					  		            UserInfo uinfo = new UserInfo();
					  		            uinfo.setUid(getLoginUser().getId());
					  		            uinfo.setAccessToken(accessToken);
					  		            userService.updateUserInfo(uinfo);
		                	    } 
			               
			  		           
		                }  
		                 
		            } catch (Exception e) {
		            }  
		          // String accessToken = refreshAccessToken(tokenPackage.getRefreshToken(),  httpServletRequest.getRequestURI());
		           return CrmUtil.invokeApiByBearerToken(tokenPackage.getAccessToken(), action, request);
			/* }catch (Exception e) {
	             //    logger.error("Failed to refresh token, request=" + JSON.toJSONString(httpServletRequest), e);
	         }*/
	          
	         
	       // }
	    }
	 
	 

	    private String refreshAccessToken(String refreshToken, String requestUrl) throws Exception {
	        List<NameValuePair> params = new ArrayList<NameValuePair>();
	        params.add(new NameValuePair("client_id",Constants.CALLCENTER.get("client_id")));
	        params.add(new NameValuePair("grant_type", "refresh_token"));
	        params.add(new NameValuePair("client_secret", Constants.CALLCENTER.get("client_secret")));
	        params.add(new NameValuePair("refresh_token", refreshToken));
	        params.add(new NameValuePair("redirect_uri", requestUrl));

	        NameValuePair[] pairs = new NameValuePair[params.size()];

	        return HttpRequester.post("http://oauth.aliyun.com/v1/token", params.toArray(pairs));
	    }
	
	
	private final  RandomString randomString = new RandomString(45);
	@RequestMapping("/auth")
    public String auth( Principal principal, HttpServletRequest httpServletRequest)
            throws UnsupportedEncodingException {
		String state = UUID.randomUUID().toString();
	    String nonce = randomString.nextString();
	    storeStateInSession(httpServletRequest.getSession(), state, nonce);
	     String ss =   "https://signin.aliyun.com/oauth2/v1/auth?response_type=code&response_mode=form_post"
	            + "&redirect_uri=" + URLEncoder.encode(Constants.CALLCENTER.get("callBak")+"/auth/callback", "UTF-8")
	            + "&client_id=" +Constants.CALLCENTER.get("client_id")
	            + "&state=" + state
	            + "&codeChallenge=" + nonce
	            + "&access_type=offline";
        return "redirect:"+ss;
    }

    private void storeStateInSession(HttpSession session, String state, String nonce) {
        Map<String, State> statesObject = getStatesFromSessionAttributes(session, true);
        statesObject.put(state,
                new State(nonce, new Date()));
    }
	
    public static final long SESSION_ATTRIBUTE_STATES_TTL_SECONDS = 300;
    public static final String SESSION_ATTRIBUTE_STATES = "states";
    public static final String CALLBACK_REQUEST_PARAMETER_STATE = "state";
	 /**
     * 阿里云呼叫中心回调地址
     */
	@RequestMapping(value="/auth/callback")
    public String callbak(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		        String requestUrl = request.getRequestURL().toString();
		        String queryString = request.getQueryString();
		        String currentUrl = requestUrl + (queryString != null ? "?" + queryString : "");

		        Map<String, String> params = request.getParameterMap().entrySet()
		                .stream()
		                .collect(Collectors.toMap(Map.Entry::getKey,
		                         e -> e.getValue()[0]));

		        AuthenticationResponse authenticationResponse = AuthenticationResponseParser.parse(new URI(currentUrl), params);

		        if (authenticationResponse instanceof AuthenticationSuccessResponse) {
		            AuthenticationSuccessResponse successResponse = (AuthenticationSuccessResponse) authenticationResponse;
		            validateAuthenticationResponse(successResponse);
		            State state = loadStateFromSession(request.getSession(),
		                    params.get(CALLBACK_REQUEST_PARAMETER_STATE));
		            if (state == null) {
		             /*   throw new CallCenterServiceException(null, "InvalidState",
		                        "Failed to validate state data received from authentication service");*/
		            }
		            String accessToken = getAccessToken(successResponse.getAuthorizationCode(), requestUrl,
		                    state.getNonce());
	/*	         UserAccount  user = getLoginUser();
		         UserInfo  uinfo =   user.getInfo();*/
		         getLoginUser().getInfo().setAccessToken(accessToken);
		         getLoginUser().setTokenPackage( TokenPackage.parse(accessToken));
		          // System.out.println("access token is {}", accessToken);
		        //    System.out.println("access token is " + accessToken);
		        //   setLoginUser(u, response);
		           UserInfo uinfo = new UserInfo();
		           uinfo.setUid(getLoginUser().getId());
		           uinfo.setAccessToken(accessToken);
		           userService.updateUserInfo(uinfo);
		           // request.getSession().setAttribute("tokenid", accessToken);
		          //    userManager.updateAccessTokenByUserName(principal.getName(), accessToken, false);
		        } else {
		            AuthenticationErrorResponse errorResponse = (AuthenticationErrorResponse) authenticationResponse;
		            /*throw new CallCenterServiceException(null, errorResponse.getErrorObject().getCode(),
		                    ("Request for authentication code failed: " +
		                            errorResponse.getErrorObject().getDescription()));*/
		        }
        return "redirect:/sys/callcenter";
    }
	
    private String getAccessToken(AuthorizationCode authorizationCode, String requestUrl, String nonce)
            throws Exception {


    	List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("client_id", Constants.CALLCENTER.get("client_id")));
        params.add(new NameValuePair("grant_type", "authorization_code"));
        params.add(new NameValuePair("client_secret", Constants.CALLCENTER.get("client_secret")));
        params.add(new NameValuePair("code", authorizationCode.getValue()));
        params.add(new NameValuePair("redirect_uri", requestUrl));
        params.add(new NameValuePair("code_verifier", nonce));
        NameValuePair[] pairs = new NameValuePair[params.size()];
        return HttpRequester.post("http://oauth.aliyun.com/v1/token", params.toArray(pairs));
    }

	
    private State loadStateFromSession(HttpSession session, String state) throws Exception {
        Map<String, State> states = getStatesFromSessionAttributes(session, false);
        if (states != null) {
            eliminateExpiredStates(states);
            State stateValue = states.get(state);
            if (stateValue != null) {
                return stateValue;
            }
        }
        return null;
    }
    
    private Map<String, State> getStatesFromSessionAttributes(HttpSession session, boolean createIfAbsence) {
        Object statesObject = session.getAttribute(SESSION_ATTRIBUTE_STATES);
        if (statesObject == null && createIfAbsence) {
            statesObject = new HashMap<String, State>(1);
            session.setAttribute(SESSION_ATTRIBUTE_STATES, statesObject);
        }
        return (Map<String, State>) statesObject;
    }

    private void eliminateExpiredStates(Map<String, State> states) {
        Iterator<Entry<String, State>> iterator = states.entrySet().iterator();
        Date now = new Date();
        while (iterator.hasNext()) {
            Map.Entry<String, State> entry = iterator.next();
            long timeElapsedSeconds = TimeUnit.MILLISECONDS.
                    toSeconds(now.getTime() - entry.getValue().getExpirationDate().getTime());
            if (timeElapsedSeconds > SESSION_ATTRIBUTE_STATES_TTL_SECONDS) {
                iterator.remove();
            }
        }
    }

    private class State {
        private String nonce;
        private Date expirationDate;

        public State(String nonce, Date expirationDate) {
            this.nonce = nonce;
            this.expirationDate = expirationDate;
        }

        public String getNonce() {
            return nonce;
        }

        public Date getExpirationDate() {
            return expirationDate;
        }
    }
	
    private void validateAuthenticationResponse(AuthenticationSuccessResponse successResponse) throws Exception {
        if (successResponse.getIDToken() != null || successResponse.getAccessToken() != null ||
                successResponse.getAuthorizationCode() == null) {
            throw new Exception(
                    "Failed to validate data received from Authorization service: unexpected set of artifacts received");
        }
    }
	
	   /**
     * 关于http参数获取 比如 http 参数 sender=xiaomao&receiver=xiaogou
     * struts自动会将参数的值 存入getModel()返回的对象的对应属性中，即xiaomao会存入message.sender属性,xiaogou会存入message.receiver属性
     * 省去了request.getParameter("sender")方式获取参数，，如果参数名在getModel()返回的对象中不存在，则需要用request.getParameter()获取
     * 其他相关*Action.java中 同理，这里做统一说明!
     */
	@RequestMapping(value="/send")
    public String send(@ModelAttribute Message message,HttpServletRequest request,HttpServletResponse response) throws Exception {
        
    	HashMap<String,Object> datamap = new HashMap<String,Object>();
    	HashMap<String,String> data = new HashMap<String,String>();
    	response.setContentType("text/json;charset=UTF-8");
		datamap.put("code", 200);
		 
		UserAccount   user = getLoginUser(); 
		try{
			message.setMid(StringUtil.getUUID());
		/*	if(message.getReceiver().equals("1")){
				message.setSender("1|"+Constants.ROBOTNAME);
				message.setFile("/images/0.jpg");//
				String msg = getRobotMessage(String.valueOf(user.getId()),message.getContent());
				message.setContent(msg);
				message.setReceiver(String.valueOf(user.getId()));
			}else{*/
				message.setSender(String.valueOf(user.getId())+"|"+user.getInfo().getName());
				//message.setSenderName(user.getInfo().getName());
				message.setFile(user.getInfo().getAvatar());
		/*	}*/
			 //向客户端 发送消息
			 messagePusher.push(message); 
	        data.put("id", message.getMid());
	        data.put("createTime", String.valueOf(message.getTimestamp()));
	        datamap.put("data", data);
		}catch(Exception e){
			
			datamap.put("code", 500);
			e.printStackTrace();
		}
       
		response.getWriter().print(new Gson().toJson(datamap));
        return null;
    }
	
	
	   /**
     * 关于http参数获取 比如 http 参数 sender=xiaomao&receiver=xiaogou
     * struts自动会将参数的值 存入getModel()返回的对象的对应属性中，即xiaomao会存入message.sender属性,xiaogou会存入message.receiver属性
     * 省去了request.getParameter("sender")方式获取参数，，如果参数名在getModel()返回的对象中不存在，则需要用request.getParameter()获取
     * 其他相关*Action.java中 同理，这里做统一说明!
     */
	@RequestMapping(value="/user/sendsysmessage")
    public String sendSysMessage(@ModelAttribute Message message,HttpServletRequest request,HttpServletResponse response) throws Exception {
        
    	HashMap<String,Object> datamap = new HashMap<String,Object>();
    	HashMap<String,String> data = new HashMap<String,String>();
    	response.setContentType("text/json;charset=UTF-8");
		datamap.put("code", 200);
		 
		
		try{
			message.setMid(StringUtil.getUUID());
			message.setFile("/images/0.jpg");//
			if(Constants.MessageType.TYPE_2.equals(message.getType()))
			{
				if(StringUtils.isEmpty(message.getReceiver())){
					List<IMSession>  sessionAll  = sessionManager.queryAll();
					if(sessionAll!=null&&sessionAll.size()>0){
						for(IMSession s:sessionAll){
							message.setReceiver(s.getAccount());
							systemMessagePusher.push(message);
						}
					}
				}else{
					 //向客户端 发送消息
					systemMessagePusher.push(message);
				}  
			} 
	        data.put("id", message.getMid());
	        data.put("createTime", String.valueOf(message.getTimestamp()));
	        datamap.put("data", data);
		}catch(Exception e){
			
			datamap.put("code", 500);
			e.printStackTrace();
		}
       
		response.getWriter().print(new Gson().toJson(datamap));
        return null;
    }
	
	/**
	 *  取得公告信息
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getannouncements", method = RequestMethod.GET,produces="text/html;charset=UTF-8" )
	@ResponseBody
	public String getAnnouncement(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
	   List<Announcement>  list = sysService.getAnnouncements();
	   return JSONArray.toJSONString(list);
	}
	/**
	 *  取得行业下的岗位
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getpositionJson", method = RequestMethod.GET,produces="text/html;charset=UTF-8" )
	@ResponseBody
	public String getPositionByCalId(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String id =  request.getParameter("id"); //行业ID
		String name=Constants.CALLING_CODE.get(id);
		Configure   cf = sysService.getConfigureByName(name);
		return JSONArray.toJSONString(cf.getItem());
	}
	/**
	 *  取得省份下的城市
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getCityJson", method = RequestMethod.GET,produces="text/html;charset=UTF-8" )
	@ResponseBody
	public String getCitysByProId(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String id =  request.getParameter("id"); //省份ID
		List<City> result =  sysService.getCityListByProId(Integer.parseInt(id));
		return JSONArray.toJSONString(result);
	}
	
	/**
	 *  取得行业网站省份及城市
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getCityJsonToCalling", method = RequestMethod.GET,produces="text/html;charset=UTF-8" )
	@ResponseBody
	public String getCitys(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
	   Connection cl =Jsoup.connect("http://www.*.cn/getCityJson");
		Document doc = cl.userAgent("Mozilla").timeout(8000).get();
		return doc.text();
	}
	 
	
	/**
	 *  取得行业网站省份及城市
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getpositionJsonToCalling", method = RequestMethod.GET,produces="text/html;charset=UTF-8" )
	@ResponseBody
	public String getPositions(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{ 
		
		String type = request.getParameter("type");
		int i = 0 ;
		if(StringUtils.isNotEmpty(type)){
			i = Integer.parseInt(type);
		}
		String path ="http://www.*.cn/";
		if(1==i){
			path =PropertyReader.loadPropertyParam("resource.properties", "carjobs");
		}else if(2==i){
			path =PropertyReader.loadPropertyParam("resource.properties", "healthjobs");
		}else if(3==i){
			path =PropertyReader.loadPropertyParam("resource.properties", "buildjobs");
		}else if(4==i){
			path =PropertyReader.loadPropertyParam("resource.properties", "bfsijobs");
		}else if(5==i){
			path =PropertyReader.loadPropertyParam("resource.properties", "epjobs");
		}
		
	   Connection cl =Jsoup.connect(path+"getpositionJson");
		Document doc = cl.userAgent("Mozilla").timeout(8000).get();
		return doc.text();
	}
	 
	
	
	
	@Autowired
	private FilesInfoService filesInfoService;
	
	/*@RequestMapping(value = "/down.json")   
	public void down(@RequestParam("fileName") String fileName,HttpServletRequest request,HttpServletResponse response) throws IOException {  
	    response.setContentType(APPLICATION);  
	    fileName = URLDecoder.decode(fileName, "utf-8");  
	    String path = getPath()+fileName;  
	    path = path.replace("%20", " ");  
	    File file = new File(path);  
	      
	    // 清空response  
	       response.reset();  
	         
	       // 设置response的Header  
	       response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"),"iso8859-1"));  
	       response.addHeader("Content-Length", "" + file.length());  
	         
	    try{  
	        //以流的形式下载文件  
	        InputStream fis = new BufferedInputStream(new FileInputStream(path));  
	        byte[] buffer = new byte[fis.available()];  
	        fis.read(buffer);  
	        fis.close();  
	          
	        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());  
	        toClient.write(buffer);  
	        toClient.flush();  
	        toClient.close();  
	    }catch(Exception e){  
	        e.printStackTrace();  
	    }  
	} */
	
	@RequestMapping(value = "/downloadfile", method = RequestMethod.GET )
	public void downLoadFile(@ModelAttribute FilesInfo fileInfo,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		try{
			if(fileInfo.getId()!=null){
				fileInfo = filesInfoService.getFileInfoByID(fileInfo);
				
				String fileName =  fileInfo.getName()== null ? "" : fileInfo.getName()+"."+fileInfo.getSuffix(); 
			    
			     File file = new File(fileInfo.getPath()+fileInfo.getNewname()+"."+fileInfo.getNewsuffix());  
			    
			    fileName = URLEncoder.encode(fileName, "UTF-8");  
			    response.reset();  
			    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");  
			    response.addHeader("Content-Length", "" + file.length());  
			    response.setContentType("application/octet-stream;charset=UTF-8");  
			    
			  //以流的形式下载文件  
		        InputStream fis = new BufferedInputStream(new FileInputStream(file));  
		        byte[] buffer = new byte[fis.available()];  
		        fis.read(buffer);  
		        fis.close();  
			    
			    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
			    outputStream.write(buffer);  
			    outputStream.flush();  
			    outputStream.close();  
			}
		}catch(Exception e){
			
		}
	}
	
	
	
	/**
	 * 监听记录剪切板内容
	 * @param log
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 */
	@RequestMapping(value = "/log/monitor", method = RequestMethod.POST )
	public void newLog(@ModelAttribute Log log,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		try{ 
			log.setUid(getLoginUser().getId());
    		log.setState(Constants.LOGSTATE.SEVEN);
    		log.setCreateuser(log.getUid());
			int  count = CommonUtil.findPhoneCount(log.getDescription());
			if(count>3){
				sysService.insertLog(log);
			} 
		}catch(Exception e){
			
		}
	}
	
	/**
	 * 文件上传
	 * @param file
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/uploadfile")
	@ResponseBody
	public String updFile( @RequestParam MultipartFile[] file,HttpServletResponse response,HttpServletRequest request) {  
	 
		 try{
			 List<MultipartFile> files = Arrays.asList(file);  
			 filesInfoService.saveFile(files);
			/* esList =   rf.readExcel(file.getInputStream(),file.getOriginalFilename(),resumeService,sysService);  
		      for(ResumeInfo resInfo:resList){
		    	   try{
		    		   resInfo.setCreateuser(String.valueOf(getLoginUser().getId()));
		    		   resInfo.setUserName(getLoginUser().getInfo().getName());
		    			  resumeService.saveResumeInfo(resInfo);
		    	   }catch(Exception e){
		    		   e.printStackTrace();
		    	   }
		    
		      } */
			//	int   result = resumeService.saveResumeInfo(res);
		        
		 }catch(Exception e){
			 e.printStackTrace();
		 }
		
		return JSONArray.toJSONString(1);
    } 
	/**
	 *  角色查询
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@Authority(validdateURL=true)
	@RequestMapping(value = "/role/getrolelist" )
	public String getRoleList(@ModelAttribute Role role,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		   Pager  pager = sysService.getRoleList(role, getSkipToPage(), pageSize);
		   pager.setUrl("/role/getrolelist");
		   request.setAttribute("pager", pager );
		   return "/sysmanage/role";
	}
	/**
	 *  角色添加
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/role/saverole" ,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String saveRole(@ModelAttribute Role role,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String productcategorys = request.getParameter("productcategory");
		int result=sysService.saveRole(role, productcategorys);
		return JSONArray.toJSONString(result);
	}
	/**
	 *  角色修改的ID查询
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/role/getrolebyid" ,produces="text/html;charset=UTF-8" )
	@ResponseBody
	public String getRoleByid(@ModelAttribute Role role,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		 Role roles= sysService.getRoleByid(role.getId());
		 return JSONArray.toJSONString(roles);
	}
	/**
	 *  角色修改的保存
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/role/updaterole" ,produces="text/html;charset=UTF-8" )
	@ResponseBody
	public String updateRole(@ModelAttribute Role role,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String productcategorys = request.getParameter("productcategory");
		int result=sysService.updateRole(role, productcategorys);
		return JSONArray.toJSONString(result);
	}
	/**
	 *  角色启用和禁用
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/role/updaterolestate" )
	public String updateRoleState(@ModelAttribute Role role,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		     int str =Integer.parseInt(request.getParameter("str"));//判断是启用还是禁用
		     sysService.updateRoleState(role.getId(),str);
		     redirectAttributes.addFlashAttribute("success", "操作成功!");
				return "redirect:/role/getrolelist";
	}
	/**
	 *  资源查询
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/systerm/getSystermlist" )
	public String getSysTermList(@ModelAttribute SysTerm systerm,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		  int pageNo = getSkipToPage();
		  String pidStr = request.getParameter("pid");
		  Long pId =0L;
		  if(!Strings.isNullOrEmpty(pidStr)){
			  pId =Long.parseLong(pidStr);
		  }
		   systerm.setPid(pId);
		   Pager  pager = sysService.getSysTermList(systerm, pageNo, pageSize);
		   pager.setUrl("/sysmanage/systerm");
		   request.setAttribute("pager", pager );
		   request.setAttribute("pid", pidStr);
		   return "/sysmanage/systerm";
	}
	/**
	 *  资源添加
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/systerm/savesysterm" ,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String saveSysTerm(@ModelAttribute SysTerm systerm,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		int result=sysService.insertSysTerm(systerm);
		return JSONArray.toJSONString(result);
	}
	/**
	 *  资源修改Id查询
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/systerm/getsystermbyid" ,produces="text/html;charset=UTF-8" )
	@ResponseBody
	public String getSysTermByid(@ModelAttribute SysTerm systerm,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		 systerm= sysService.getSysTermByid(systerm.getId());
		 return JSONArray.toJSONString(systerm);
	}
	/**
	 *  资源修改保存
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/systerm/updatesysterm" ,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String updateSysTerm(@ModelAttribute SysTerm systerm,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		int result=sysService.updateSysTerm(systerm);
		return JSONArray.toJSONString(result); 
	}
	/**
	 *  资源绑定查询
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/systerm/selectsysterm" ,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String selectSysTerm(@ModelAttribute SysTerm systerm,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		 int rid= Integer.parseInt(request.getParameter("rid"));
		List <SysTerm> result=sysService.getSysTermBound(systerm,rid);
		 return JSONArray.toJSONString(result);
	}
	/**
	 *  资源绑定保存
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/systerm/savasysterm" ,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String savaSysTerm(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		   String rid= request.getParameter("rid");
		   String tids= request.getParameter("tids");
		   int result=sysService.saveSysTermBound(rid,tids);
		   return JSONArray.toJSONString(result);
	}
	/**
	 *  系统消息管理查询
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/systerm/getsysmessage" ,produces="text/html;charset=UTF-8")
	public String getSysMessage(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		 request.setAttribute("userlist",sessionManager.queryAll());
		   return "/sysmanage/message";
	}
	/**
	 *  资源分配，查询部门下用户
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	/*@RequestMapping(value = "/systerm/getUserandCustomer" ,produces="text/html;charset=UTF-8")
	public String getUserandCustomer(@ModelAttribute CustomerInfo info,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		List<UserInfo> userlist=userService.getUserListByDeptId(getLoginUser().getInfo().getDeptid());
		if(StringUtils.isEmpty(info.getCreateuser())){
			info.setCreateuser(String.valueOf(getLoginUser().getId()));
		}
		if(info.getState()==null){
			info.setState(10);//设置为所属状态条件
		}
		
		Pager  pager = sysService.getUserandCustomerList(info, getSkipToPage(), 40);
		 Map<String,Object> params = new HashMap<String,Object>();
		 params.put("keyWord", info.getKeyWord());
		 params.put("createuser", info.getCreateuser());
		 params.put("calling", info.getCalling());
		 params.put("productcategory", info.getProductcategory());
		 params.put("state", info.getState());
		 pager.setParams(params);
		 pager.setUrl("/systerm/getUserandCustomer");
		 request.setAttribute("userlist", userlist );
		    request.setAttribute("pager", pager );
		   return "/sysmanage/customerdistribute";
	}*/
	/**
	 *  保存客户分配
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/systerm/savecustomercreatuserupdate" ,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String saveCustomerCreatuserUpdate(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		 String ids= request.getParameter("id");
		 String uid= request.getParameter("uid");
		Long infoid= getLoginUser().getId();
		int result= sysService.saveCustomerCreatuserUpdate(ids,uid,infoid);
		 return JSONArray.toJSONString(result);
	}
	/**
	 *  保存条件查询的所有客户分配
	 * @param response
	 * @param request
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 */
	/*@RequestMapping(value = "/systerm/savecustomercreatuserupdateall" ,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String saveCustomerCreatuserUpdateAll(@ModelAttribute CustomerInfo info,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		 String uid= request.getParameter("uid");
			Long infoid= getLoginUser().getId();
		if(StringUtils.isEmpty(info.getCreateuser())){
			info.setCreateuser(String.valueOf(infoid));
		}
		if(info.getState()==null){
			info.setState(10);//设置为所属状态条件
		}
		
		Pager  pager = sysService.getUserandCustomerList(info, getSkipToPage(), 10000000);
		List<CustomerInfo> list=(List<CustomerInfo>) pager.getResultList();
		
		int result= sysService.saveCustomerCreatuserUpdateAll(list, uid, infoid);
		 return JSONArray.toJSONString(result);
	}*/
	
	
	/**
	 * 锁屏密码比较
	 */
	@RequestMapping(value="/systerm/checklockpwd")
	@ResponseBody
	public String checkLockPwd(String pwds,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		String pwd = getLoginUser().getPassword();
		pwd = Constants.SECURITY.decryptString(pwd);
		if (pwd.equals(pwds)){
			return JSON.toJSONString(1);
		} else {
			return JSON.toJSONString(0);
		}
	}
	
	/**
	 * 进入部门管理页面
	 * */
	@Authority(validdateURL=true)
	@RequestMapping(value = "/systerm/getdepartmentlist{k}" )
	public String getDepartMentList(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		Long pid = 0L;
		if (k != null && k.length() > 0) {
			pid = Long.parseLong(k);
		}
		Department d = new Department();
		d.setParentid(pid);
		Pager pager = new Pager(getSkipToPage(), pageSize);
		pager.setResultList(sysService.getDepartmentListAll(d));
		pager.setUrl("/systerm/getdepartmentlist"+k);
		request.setAttribute("pager", pager );
		return "/sysmanage/department";
	}
	
	/**
	 * 添加部门(加修改部门)
	 * */
	@RequestMapping(value="/systerm/adddepartment")
	@ResponseBody
	public String addDepartment(String name,String parentid,Integer type,Long id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		Department d = new Department();
		d.setParentid(Long.parseLong(parentid));
		d.setName(name);
		d.setCount(0);
		if (type == 0) {
			if (Long.parseLong(parentid) == 0) {
				d.setLevel(1);
			}
			sysService.addDepartment(d);
		} else {
			d.setId(id);
			sysService.updateDepartment(d);
		}
		return JSON.toJSONString(1);
	}
	
	/**
	 * 删除部门
	 * */
	@RequestMapping(value="/systerm/deletedepartment")
	@ResponseBody
	public String deleteDepartment(Long id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		//我知道了这个部门的部门id,那删除这个部门，所有这个部门下的子部门都要被删除
		sysService.deleteDepartment(id);
		return JSON.toJSONString(1);
	}
	
	
	/**
	 * 进入配置管理页面
	 * /systemer/configurelistp_{page}c_{cid}r_{parentid}
	 * */
	@RequestMapping(value="/systemer/configurelist{k}")
	public String intoConfigureList(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		Long cid = 0L;
		Long pid = null;
		Integer pageNo = getSkipToPage();
		if (k != null) {
			String key[] = k.split("_");
			for (String kk : key) {
				if (kk.indexOf("c") > -1 ) {
					cid = Long.parseLong(kk.replace("c", ""));
				} else if (kk.indexOf("r") > -1) {
					if (kk.length() > 1) {
						pid = Long.parseLong(kk.replace("r", ""));
					}
				} else if (kk.indexOf("p") > -1) {
					pageNo = Integer.parseInt(kk.replace("p", ""));
				}
			}
		}
		
		Pager pager = new Pager(getSkipToPage(), pageSize);
		if (cid == 0L) {
			//获取配置项
			List<Configure> list = sysService.getConfigureList(getSkipToPage(), pageSize);
			pager.setResultList(list);
			if (pid == null) {
				pager.setUrl("/systemer/configurelistc"+cid+"_p"+pageNo);
			} else {
				pager.setUrl("/systemer/configurelistc"+cid+"_r"+pid+"_p"+pageNo);
			}
			
		} else {
			//根据cid获取配置项详情
			ConfigureItem ci = new ConfigureItem();
			ci.setPid(pid);
			ci.setCid(cid);
			List<ConfigureItem> list = sysService.getConfigureItemList(ci,pageNo, pageSize);
			pager.setResultList(list);
			if (pid == null) {
				pager.setUrl("/systemer/configurelistc"+cid+"_p"+pageNo);
			} else {
				pager.setUrl("/systemer/configurelistc"+cid+"_r"+pid+"_p"+pageNo);
			}
		}
		request.setAttribute("pager", pager);
		request.setAttribute("cid", cid);
		request.setAttribute("pid", pid);
		return "/sysmanage/configure";
	}
	
	/**
	 * 获取排序号
	 * */
	@RequestMapping(value="/systerm/getmaxordernumber")
	@ResponseBody
	public String getMaxOrderNum(Long cid,Long pid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		ConfigureItem ci = new ConfigureItem();
		ci.setCid(cid);
		if (pid != null && pid.toString().length() > 0) {
			ci.setPid(pid);
		}
		Integer result = sysService.getMaxOrderNumber(ci);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 添加或修改配置
	 * 根据type来判断是新增（0）还是修改（1）
	 * */
	@RequestMapping(value="/systerm/addconfigure")
	@ResponseBody
	public String addConfigure(String name,String code,Integer type,Long id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		Configure c = new Configure();
		c.setCode(code);
		c.setName(name);
		if (type == 0) {
			sysService.addConfigure(c);
		} else {
			c.setId(id);
			sysService.updateConfigure(c);
		}
		return JSON.toJSONString(0);
	}
	
	/**
	 * 添加或修改配置详情
	 * 根据type来判断是新增（0）还是修改（1）
	 * */
	@RequestMapping(value="/systerm/addconfigureitem")
	@ResponseBody
	public String addConfigureItem(String name,String value,String ordernumber,Long cid,Long pid,Integer type,Long id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		ConfigureItem ci = new ConfigureItem();
		ci.setValue(value);
		ci.setName(name);
		if (ordernumber != null) {
			Pattern pattern = Pattern.compile("[0-9]*");
			Matcher isNum = pattern.matcher(ordernumber);
			if(isNum.matches()){
				ci.setOrdernumber(Integer.parseInt(ordernumber));
			}
		}
		ci.setCid(cid);
		if (pid == null) {
			pid = 0L;
		}
		ci.setPid(pid);
		if (type == 0) {
			sysService.addConfigureItem(ci);
		} else {
			ci.setId(id);
			sysService.updateConfigureItem(ci);
		}
		return JSON.toJSONString(0);
	}
	
	/**
	 * 删除配置项或配置详情
	 * 根据type判断是配置项（1）还是配置详情（2）
	 * */
	@RequestMapping(value="/systerm/deleteconfig")
	@ResponseBody
	public String deleteConfigure(Integer type,Long cid,Long id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		if (type == 1) {
			//配置项删除
			Configure c = new Configure();
			c.setId(cid);
			sysService.deleteConfigure(c);
		} else {
			//配置项详情删除
			ConfigureItem ci = new ConfigureItem();
			ci.setId(id);
			sysService.deleteConfigureItem(ci);
		}
		return JSON.toJSONString(0);
	}
	
	
	/**
	 * 审批配置
	 * */
	@RequestMapping(value="/systerm/approveConfig{k}")
	public String approveConfigPage(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		Integer pageNo = getSkipToPage();
		Pager pager = new Pager(pageNo, pageSize);
		if (Long.parseLong(k) == 0) {
			ApproveConfigure ac = new ApproveConfigure();
			//获取审批配置表列表
			List<ApproveConfigure> list = approveConfigureService.getAllApproveConfigureList(ac, pageNo, pageSize);
			pager.setResultList(list);
		} else {
			ApproveConfigureItem aci = new ApproveConfigureItem();
			aci.setAcid(Integer.parseInt(k));
			List<ApproveConfigureItem> list = approveConfigureService.getApproveUserListByAcid(aci, pageNo, pageSize);
			pager.setResultList(list);
		}
		request.setAttribute("pager", pager);
		request.setAttribute("acid", k);
		return "/sysmanage/approveconfig";
	}
	
	/**
	 * 获取某一审批项审批人数
	 * */
	@RequestMapping(value="/systerm/getapproveusercount")
	@ResponseBody
	public String getApproveUserCount(Integer acid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		int result = approveConfigureService.getApproveUserCount(acid);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 新增或修改审批配置
	 * 0新增 1修改
	 * 现在有一个问题，我新增或修改一个审批人，然后我改变了他的审批等级，然后相应的，其他人的审批等级也就会发生变化
		那现在就要看看有哪些情况了：
			新增：
				不改变位置，就在最后一位，皆大欢喜，不用改什么
				改变位置：改变位置之前的不用变，后面的每个level+1
			修改：
				不改变位置，也就是旧排位跟新排位一样，皆大欢喜，不用改什么。
				向前改变：改变位置之前不变，原先位置之后不变，只有位置之间的排序改变
				向后改变：原先位置之前不变，改变位置之后不变，只有位置之间的排序改变
		所以很关键的两个数据就是：原始位置，改变之后的位置，根据这两个值来确定范围
	 * */
	@RequestMapping(value="/systerm/changeapproconfig")
	@ResponseBody
	public String changeApproConfig(Long id,Integer acid,Long uid,Integer level,Integer type,Integer oldlevel,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		ApproveConfigureItem aci = new ApproveConfigureItem();
		aci.setUid(uid);
		aci.setLevel(level);
		aci.setAcid(acid);
		aci.setOldlevel(oldlevel);
		if (type == 1) {
			aci.setId(id);
		}
		int result = approveConfigureService.updateApproveUser(aci, type);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 删除审核员
	 * */
	@RequestMapping(value="/systerm/deleteapproconfig")
	@ResponseBody
	public String deleteApproveUser(ApproveConfigureItem aci,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		int result = approveConfigureService.deleteApproveUser(aci);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 获取所有的省份列表
	 * */
	@RequestMapping(value="/systerm/getallprovincelist", produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getallprovincelist(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		List<Province> list = sysService.getProvinceList();
		return JSON.toJSONString(list);
	}
	
	

}
